package com.xwltz.rbac.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xwltz.core.domain.SimpleActionResult;
import com.xwltz.core.utils.BeanUtils;
import com.xwltz.core.utils.CommonUtils;
import com.xwltz.core.utils.SecureUtils;
import com.xwltz.core.utils.StringUtils;
import com.xwltz.database.mybatisplus.core.ServicePlusImpl;
import com.xwltz.rbac.auth.SetCommonFiled;
import com.xwltz.rbac.domain.MemberEntity;
import com.xwltz.rbac.mapper.MemberMapper;
import com.xwltz.rbac.model.request.LoginRequest;
import com.xwltz.rbac.model.request.MemberRequest;
import com.xwltz.rbac.service.MemberService;
import com.xwltz.rbac.model.response.MemberResponse;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @description MemberServiceImpl
 * @information on version 1.0 be created by @xwltz at 2022/1/15 16:50
 */

@Service
@DS("slave")
public class MemberServiceImpl extends ServicePlusImpl<MemberMapper, MemberEntity, MemberResponse> implements MemberService {

	@Override
	public SimpleActionResult memberLogin(LoginRequest request) {
		if (StringUtils.isEmpty(request.getUserName())) {
			return SimpleActionResult.error("账号不能为空");
		}

		if (StringUtils.isEmpty(request.getPassword())) {
			return SimpleActionResult.error("密码不能为空");
		}

		MemberResponse member = getVoOne(new LambdaQueryWrapper<MemberEntity>().eq(MemberEntity::getUserName, request.getUserName()).last("limit 1"));
		if (StringUtils.isNull(member)) {
			return SimpleActionResult.error("用户不存在");
		}

		if (!member.getPassword().equals(SecureUtils.password(request.getPassword(), member.getSalt()))) {
			return SimpleActionResult.error("密码不正确");
		}

		if (member.getStatus().equals(1)) {
			return SimpleActionResult.error("您的账号已被禁用");
		}

		// 授权登录
		StpUtil.login(member.getId());

		var token = StpUtil.getTokenInfo();
		var ss = StpUtil.getLoginIdByToken(token.getTokenValue());
		System.out.println(ss);
		return SimpleActionResult.success(token);
	}

	@Override
	public SimpleActionResult memberSave(MemberRequest request) {
		MemberEntity model = BeanUtils.oneCopy(request, null, this.entityClass);
		// 计算密码
		var salt = CommonUtils.getSaltStr();
		var pwd = SecureUtils.password(request.getPassword(), salt);
		model.setSalt(salt);
		model.setPassword(pwd);

		model.setPwdUpdateDate(LocalDateTime.now());

		// 必须完成，否则 创建人、创建时间、修改人、修改时间均为 null 值

		new SetCommonFiled<MemberEntity>().set(model);
		boolean isSuccess = saveOrUpdate(model);
		return SimpleActionResult.result(isSuccess);
	}
}
